package main

import (
	"database/sql"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	_ "github.com/go-sql-driver/mysql"
	"github.com/gocolly/colly/v2"
)

func main() {
	// 连接 MariaDB 数据库
	log.Printf("Start... OK ")
	dsn := "root:123@tcp(localhost:3306)/dcp-cloud"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("无法连接到数据库: %v", err)
	}
	defer db.Close()
	log.Printf("Database connect OK ")

	// 执行 SQL 查询
	rows, err := db.Query(`
        SELECT 
            CONCAT('https://www.dongchedi.com/series-', fcmi.series_id, '/images/wg-', fcmi.id, '-x-') AS aurl,
            CONCAT(fsi.outter_name, '_', fcmi.display_name) AS dirName
        FROM 
            fs_car_model_info fcmi, fs_car_series_info fsi 
        WHERE
            fcmi.series_id = 3068 AND fcmi.deleted = 0 AND fcmi.series_id = fsi.id limit 1;
    `)
	if err != nil {
		log.Fatalf("执行查询失败: %v", err)
	}
	defer rows.Close()
	log.Printf("SQL... OK ")

	// 遍历查询结果
	for rows.Next() {
		var aurl, dirName string
		if err := rows.Scan(&aurl, &dirName); err != nil {
			log.Printf("扫描行失败: %v", err)
			continue
		}

		// 创建保存图片的文件夹
		if err := os.MkdirAll(dirName, os.ModePerm); err != nil {
			log.Printf("创建文件夹失败: %v", err)
			continue
		}

		// 循环抓取图片
		for i := 0; ; i++ {
			url := aurl + strconv.Itoa(i)
			c := colly.NewCollector()
			log.Printf("正在请求 %s ", url)

			var found bool
			//c.OnHTML("div.head-image_image__2b9RI img", func(e *colly.HTMLElement) {
			c.OnHTML("img[width='1254']", func(e *colly.HTMLElement) {
				//className := e.Attr("width")
				//if className == "1254" {
				found = true
				log.Printf("1- 图片url: %s", url)
				imgSrc := e.Attr("src")
				if imgSrc != "" {
					downloadImage(imgSrc, dirName)
				}
				//} else {
				//	log.Printf("未找到图片元素,当前是：%s", className)
				//}
			})

			c.OnError(func(r *colly.Response, err error) {
				log.Printf("请求 %s 失败: %v", url, err)
			})

			if err := c.Visit(url); err != nil {
				log.Printf("访问 %s 失败: %v", url, err)
				break
			}

			if !found {
				break
			}
		}
	}

	if err := rows.Err(); err != nil {
		log.Fatalf("遍历行时出错: %v", err)
	}
}

func downloadImage(url, dir string) {
	log.Printf("2- 图片url: %s", url)

	resp, err := http.Get(url)
	if err != nil {
		log.Printf("下载图片失败: %v", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Printf("下载图片时收到非 200 状态码: %d", resp.StatusCode)
		return
	}

	// 获取图片文件名
	fileName := filepath.Base(url)
	filePath := filepath.Join(dir, fileName)

	file, err := os.Create(filePath)
	if err != nil {
		log.Printf("创建文件失败: %v", err)
		return
	}
	defer file.Close()

	_, err = io.Copy(file, resp.Body)
	if err != nil {
		log.Printf("写入文件失败: %v", err)
		return
	}

	fmt.Printf("图片下载成功: %s\n", filePath)
}
